<template>
  <BasicModal v-bind="$attrs" @ok="handleOk" @register="registerModal">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import MD5 from 'crypto-js/md5';
  import { cloneDeep } from 'lodash-es';
  import { modalFormSchema } from './data';
  import mcApi from 'mc-c2b2m-operator-api';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useUserStore } from '@/store/modules/user';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { AppAuthMethodModel } from 'mc-c2b2m-operator-api/types/sys';

  const { SysModule, SystemModule } = mcApi;
  const { OrgApi, UserApi: UserApi2 } = SystemModule;
  const { UserApi } = SysModule;

  const userStore = useUserStore();
  const { orgId } = userStore.getUserInfo;

  const [registerForm, { resetFields, setFieldsValue, validate, resetSchema }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 22 },
    showActionButtonGroup: false,
  });

  const ifUpdate = ref<boolean>(false);
  const authMethodId = ref<string>('');
  const [registerModal, { setModalProps }] = useModalInner(async (data: any) => {
    await resetFields();
    ifUpdate.value = !!data.ifUpdate;
    const formSchema = cloneDeep(modalFormSchema);
    ifUpdate.value && formSchema.splice(1, 1);
    await resetSchema(formSchema);
    setModalProps({
      // width: 555,
      minHeight: 50,
      confirmLoading: false,
      title: ifUpdate.value ? '修改密码' : '新增用户',
    });
    await setFieldsValue(data);
    // 获取认证方式id
    UserApi.getAppAuthMethodList().then((res: AppAuthMethodModel[]) => {
      authMethodId.value = res?.[0]?.authMethodId;
    });
  });

  const { createMessage } = useMessage();
  const emits = defineEmits(['success']);
  async function handleOk() {
    try {
      if (!authMethodId.value) {
        createMessage.error('获取认证方式id失败！');
        return;
      }
      const values: any = await validate();
      setModalProps({ confirmLoading: true });
      const { account, password } = values;
      if (ifUpdate.value) {
        const model = {
          authMethodId: authMethodId.value,
          authAccountFields: [{ key: 'newPassword', value: password }],
        };
        await UserApi2.updateUserPassword(model);
        createMessage.success('修改密码成功！');
        emits('success');
      } else {
        const model = {
          authMethodId: authMethodId.value,
          authAccountFields: [
            { key: 'account', value: account },
            { key: 'password', value: password },
            { key: 'encodedPassword', value: MD5(password).toString() },
          ],
        };
        // 先创建账户
        const accountRes = await OrgApi.createAccount(model);
        values.operatorId = accountRes.id;
        values.orgId = orgId;
        // 根据新账号添加组织成员
        await OrgApi.applyMemberToOrg(values);
        createMessage.success('新增成功！');
        emits('success');
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style scoped lang="less"></style>
